package com.webster.isw.core.paging.service.impl;

import com.webster.isw.core.config.SysParam;
import com.webster.isw.core.mapper.PageResultMapper;
import com.webster.isw.core.paging.PageResult;
import com.webster.isw.core.paging.service.PageResultService;
import com.webster.isw.core.service.ParamService;
import com.webster.isw.core.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Map;

/**
 * 分页服务
 * Created by Webster on 16/5/7.
 */
@Service("pageResultService")
public class PageResultServiceImpl extends BaseServiceImpl implements PageResultService {
    /**
     * Field iq: 查询接口
     */
    @Autowired
    private PageResultMapper pageResultMapper;

    /**
     * Field paramService: 参数获取服务
     */
    @Autowired
    private ParamService paramService;

    /**
     * Description: 分页方法
     *
     * @param sql sql语句
     * @param pageSize 页大小
     * @param curPage 第几页
     * @return 分页结果集
     * @throws Exception 未知异常
     */
    public PageResult pageQuery(String sql, int pageSize, int curPage) throws Exception {
        if (pageSize < 1) {
            final String PAGE_SIZE = paramService.getSysParamPreFerDefault(SysParam.PAGE_SIZE.name());
            pageSize = new Integer(PAGE_SIZE);
        }
        if (curPage < 1) {
            curPage = 1;
        }
        final PageResult RE_PAGE_RESULT = new PageResult();
        RE_PAGE_RESULT.setPageSize(pageSize); // 设置每页条数
        RE_PAGE_RESULT.setTotalRecords(pageResultMapper.getCount(sql)); // 设置总条数
        if (RE_PAGE_RESULT.getTotalRecords() > 0) {
            final int TOTAL_PAGES = RE_PAGE_RESULT.getTotalRecords() / pageSize
                    + ((RE_PAGE_RESULT.getTotalRecords() % pageSize > 0) ? 1 : 0);
            RE_PAGE_RESULT.setTotalPages(TOTAL_PAGES); // 设置总页数
            if (curPage > RE_PAGE_RESULT.getTotalPages()) {
                RE_PAGE_RESULT.setCurPage(RE_PAGE_RESULT.getTotalPages());
            } else {
                RE_PAGE_RESULT.setCurPage(curPage);
            }
            RE_PAGE_RESULT.setRecords(pageResultMapper.pageQuery(sql, pageSize, (curPage - 1) * pageSize));
        } else {
            RE_PAGE_RESULT.setCurPage(0);
            RE_PAGE_RESULT.setTotalPages(0);
            RE_PAGE_RESULT.setRecords(new ArrayList<Map<String, Object>>());
        }
        return RE_PAGE_RESULT;
    }
}


